package com.leyou.trade.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.utils.UserContext;
import com.leyou.trade.entity.CartItem;
import com.leyou.trade.repository.CartRepository;
import com.leyou.trade.service.CartService;
import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    private CartRepository cartRepository;

    @Override
    public void addCart(CartItem cartItem) {


        //购物车商品的唯一id（userId+skuId）
        String id = createId(cartItem.getSkuId());

        Optional<CartItem> optional = this.cartRepository.findById(id);

        //有值，表示加入过
        if (optional.isPresent()){
            CartItem cart = optional.get();
            //修改数量
            cart.setNum(cart.getNum()+cartItem.getNum());
            //刷新修改时间
            cart.setUpdateTime(new Date());

            this.cartRepository.save(cart);
        }else{
            cartItem.setId(createId(cartItem.getSkuId()));
            cartItem.setUserId(UserContext.getUser().getId());
            cartItem.setUpdateTime(new Date());
            this.cartRepository.save(cartItem);
        }

    }

    @Override
    public List<CartItem> listMongoCart() {

        List<CartItem> cartItems = this.cartRepository.findByUserId(UserContext.getUser().getId());


        return cartItems;
    }

    @Override
    public void deleteBySkuId(Long skuId) {
        this.cartRepository.deleteById(createId(skuId));
    }


    private String createId(Long skuId) {
        //%d表示占位符，d表示数值占位。u30s10086
        return String.format("u%ds%d", UserContext.getUser().getId(), skuId);
    }
}
